package com.boomsecret.netty.chatv2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Objects;

/**
 * @author: wangjinliang
 * @date: 2020/10/27
 */
public class NettyChatServerHandlerV2 extends ChannelInboundHandlerAdapter {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(existChannel -> {
            if (!Objects.equals(existChannel, channel)) {
                existChannel.writeAndFlush(Unpooled.copiedBuffer((channel.hashCode() + " 下线了").getBytes()));
            }
        });
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        ByteBuf byteBuf = (ByteBuf) msg;
        String content = byteBuf.toString(CharsetUtil.UTF_8);
        channelGroup.forEach(existChannel -> {
            if (!Objects.equals(channel, existChannel)) {
                existChannel.writeAndFlush(Unpooled.copiedBuffer((channel.hashCode() + "说：" + content).getBytes()));
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(Unpooled.copiedBuffer((channel.hashCode() + " 上线啦").getBytes()));
        channelGroup.add(channel);
    }
}
